package gui.form;

import gui.ImageListShower;
import gui.image.AlbumImageList;
import gui.treenode.AlbumTreeNode;
import gui.treenode.RootAlbumTreeNode;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.SpringLayout;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import org.ini4j.Profile;
import org.ini4j.Profile.Section;
import process.ImportManager;
import qviewer.ServiceManager;
import util.MyIniSection;
import util.OShandler;

/**
 *
 * @author Quân
 */
public class MainForm extends javax.swing.JFrame {

    private MutableTreeNode folderNode;
    private RootAlbumTreeNode albumNode;

    /**
     * Creates new form main
     */
    public MainForm() {
        initComponents();
        this.setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH);
        loadTreeView();
        initGUI();
        this.jScrollPaneRight.getVerticalScrollBar().setUnitIncrement(20);
        ImportManager importManager = new ImportManager(jPanelRight);
        importManager.Load();
        ServiceManager.getInstance().setImportManager(importManager);
    }

    private void initGUI() {
        ImageListShower shower = new ImageListShower();
        SpringLayout sl = new SpringLayout();
        jLayeredPane.setLayout(sl);
        jLayeredPane.add(shower, new Integer(2));
        sl.putConstraint(SpringLayout.NORTH, shower, 5, SpringLayout.NORTH, jLayeredPane);
        sl.putConstraint(SpringLayout.WEST, shower, 5, SpringLayout.WEST, jLayeredPane);
        sl.putConstraint(SpringLayout.EAST, shower, -5, SpringLayout.EAST, jLayeredPane);
        sl.putConstraint(SpringLayout.SOUTH, shower, -5, SpringLayout.SOUTH, jLayeredPane);
        shower.setVisible(false);
        ServiceManager.getInstance().setShower(shower);

        JScrollPane scrollPane = new JScrollPane(jPanelRight, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.getVerticalScrollBar().setUnitIncrement(16);
        sl.putConstraint(SpringLayout.NORTH, scrollPane, 5, SpringLayout.NORTH, jLayeredPane);
        sl.putConstraint(SpringLayout.WEST, scrollPane, 5, SpringLayout.WEST, jLayeredPane);
        sl.putConstraint(SpringLayout.EAST, scrollPane, -5, SpringLayout.EAST, jLayeredPane);
        sl.putConstraint(SpringLayout.SOUTH, scrollPane, -5, SpringLayout.SOUTH, jLayeredPane);
        jLayeredPane.add(scrollPane);
    }

    public final void loadTreeView() {
        this.jTree.setRootVisible(false);
        this.jTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        DefaultTreeModel model = (DefaultTreeModel) jTree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        root.removeAllChildren();
        folderNode = new DefaultMutableTreeNode("Folder");
        root.add(folderNode);
        albumNode = new RootAlbumTreeNode("Album");
        root.add(albumNode);
        MutableTreeNode poople = new DefaultMutableTreeNode("Poople");
        root.add(poople);
        model.reload(root);
        expandAll();
    }

    public void expandAll() {
        int row = 0;
        while (row < this.jTree.getRowCount()) {
            this.jTree.expandRow(row);
            row++;
        }
    }

    public void jTreeReload() {
        DefaultTreeModel model = (DefaultTreeModel) jTree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
        model.reload(root);
        expandAll();
    }

    public void addAlbum() {
        String albumName = JOptionPane.showInputDialog(rootPane, "Please input your album name:");
        if (albumName != null) {
            UUID uniqueKey = UUID.randomUUID();

            OShandler oShandler = OShandler.getInstance();
            File app = oShandler.getAppDataFolder();
            File root = new File(app, qviewer.QViewer.myName);
            File file = new File(root, uniqueKey.toString());
            AlbumImageList imageList = new AlbumImageList(file, albumName);

            Section section = qviewer.QViewer.iniAlbum.add(uniqueKey.toString());
            section.add(MyIniSection.NodeName, albumName);
            section.add(MyIniSection.NodePath, root.getPath() + "\\" + uniqueKey.toString());
            try {
                qviewer.QViewer.iniAlbum.store();
            } catch (IOException ex) {
                Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
            }

            AlbumTreeNode node = new AlbumTreeNode(albumName);
            MyIniSection album = new MyIniSection(section, imageList);
            node.setUserObject(album);
            albumNode.insert(node, albumNode.getChildCount());

            ServiceManager.getInstance().getImportManager().getAlbums().add(album);

            this.jTreeReload();
            jPanelRight.add(imageList);
            jPanelRight.updateUI();
        }
    }

    public void deleteAlbum() {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree.getLastSelectedPathComponent();
        MyIniSection myIniSection = (MyIniSection) node.getUserObject();
        Profile.Section section = myIniSection.getSection();
        qviewer.QViewer.iniAlbum.remove(section);

        DefaultTreeModel model = (DefaultTreeModel) jTree.getModel();
        model.removeNodeFromParent(node);
        try {
            qviewer.QViewer.iniAlbum.store();
            ServiceManager.getInstance().getImportManager().getAlbums().remove(myIniSection);
            jPanelRight.remove(myIniSection.getImageList());
            jPanelRight.updateUI();
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane = new javax.swing.JSplitPane();
        jScrollPaneLeft = new javax.swing.JScrollPane();
        jTree = new gui.MyTree();
        jScrollPaneRight = new javax.swing.JScrollPane();
        jLayeredPane = new javax.swing.JLayeredPane();
        jPanelRight = new javax.swing.JPanel();
        jToolBarProcess = new javax.swing.JToolBar();
        jToolBarMenu = new javax.swing.JToolBar();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        openMenuItem = new javax.swing.JMenuItem();
        saveMenuItem = new javax.swing.JMenuItem();
        saveAsMenuItem = new javax.swing.JMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        editMenu = new javax.swing.JMenu();
        cutMenuItem = new javax.swing.JMenuItem();
        copyMenuItem = new javax.swing.JMenuItem();
        pasteMenuItem = new javax.swing.JMenuItem();
        deleteMenuItem = new javax.swing.JMenuItem();
        helpMenu = new javax.swing.JMenu();
        contentsMenuItem = new javax.swing.JMenuItem();
        aboutMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("qViewer");

        jSplitPane.setDividerLocation(160);
        jSplitPane.setDividerSize(2);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        jTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        jScrollPaneLeft.setViewportView(jTree);

        jSplitPane.setLeftComponent(jScrollPaneLeft);

        jScrollPaneRight.setAutoscrolls(true);

        jPanelRight.setLayout(new javax.swing.BoxLayout(jPanelRight, javax.swing.BoxLayout.PAGE_AXIS));
        jPanelRight.setBounds(10, 10, 480, 260);
        jLayeredPane.add(jPanelRight, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jScrollPaneRight.setViewportView(jLayeredPane);

        jSplitPane.setRightComponent(jScrollPaneRight);

        jToolBarProcess.setFloatable(false);
        jToolBarProcess.setRollover(true);

        jToolBarMenu.setFloatable(false);
        jToolBarMenu.setRollover(true);

        jButton2.setText("Import");
        jButton2.setFocusable(false);
        jButton2.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton2.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jToolBarMenu.add(jButton2);

        jButton1.setText("Remove");
        jButton1.setFocusable(false);
        jButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jToolBarMenu.add(jButton1);

        fileMenu.setMnemonic('f');
        fileMenu.setText("File");

        jMenuItem1.setText("New Album");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem1);

        openMenuItem.setMnemonic('o');
        openMenuItem.setText("Open");
        fileMenu.add(openMenuItem);

        saveMenuItem.setMnemonic('s');
        saveMenuItem.setText("Save");
        fileMenu.add(saveMenuItem);

        saveAsMenuItem.setMnemonic('a');
        saveAsMenuItem.setText("Save As ...");
        saveAsMenuItem.setDisplayedMnemonicIndex(5);
        fileMenu.add(saveAsMenuItem);

        exitMenuItem.setMnemonic('x');
        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        editMenu.setMnemonic('e');
        editMenu.setText("Edit");

        cutMenuItem.setMnemonic('t');
        cutMenuItem.setText("Cut");
        editMenu.add(cutMenuItem);

        copyMenuItem.setMnemonic('y');
        copyMenuItem.setText("Copy");
        editMenu.add(copyMenuItem);

        pasteMenuItem.setMnemonic('p');
        pasteMenuItem.setText("Paste");
        editMenu.add(pasteMenuItem);

        deleteMenuItem.setMnemonic('d');
        deleteMenuItem.setText("Delete");
        editMenu.add(deleteMenuItem);

        menuBar.add(editMenu);

        helpMenu.setMnemonic('h');
        helpMenu.setText("Help");

        contentsMenuItem.setMnemonic('c');
        contentsMenuItem.setText("Contents");
        helpMenu.add(contentsMenuItem);

        aboutMenuItem.setMnemonic('a');
        aboutMenuItem.setText("About");
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 661, Short.MAX_VALUE)
            .addComponent(jToolBarProcess, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jToolBarMenu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBarMenu, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSplitPane, javax.swing.GroupLayout.DEFAULT_SIZE, 298, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToolBarProcess, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        OShandler os = OShandler.getInstance();
        File userHome = os.getOSDefaultFolder();

        JFileChooser jFileChooser = new JFileChooser(userHome);
        jFileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int result = jFileChooser.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = jFileChooser.getSelectedFile();
            try {
                ServiceManager.getInstance().getImportManager().Import(file);
            } catch (Exception ex) {
                Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed
    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
    }//GEN-LAST:event_jMenuItem1ActionPerformed
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree.getLastSelectedPathComponent();

        MyIniSection myIniSection = (MyIniSection) node.getUserObject();
        Section section = myIniSection.getSection();
        qviewer.QViewer.iniFolder.remove(section);

        DefaultTreeModel model = (DefaultTreeModel) jTree.getModel();
        model.removeNodeFromParent(node);
        try {
            qviewer.QViewer.iniFolder.store();
            jPanelRight.remove(myIniSection.getImageList());
            jPanelRight.updateUI();
        } catch (IOException ex) {
            Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem aboutMenuItem;
    private javax.swing.JMenuItem contentsMenuItem;
    private javax.swing.JMenuItem copyMenuItem;
    private javax.swing.JMenuItem cutMenuItem;
    private javax.swing.JMenuItem deleteMenuItem;
    private javax.swing.JMenu editMenu;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JMenu helpMenu;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLayeredPane jLayeredPane;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanelRight;
    private javax.swing.JScrollPane jScrollPaneLeft;
    private javax.swing.JScrollPane jScrollPaneRight;
    private javax.swing.JSplitPane jSplitPane;
    private javax.swing.JToolBar jToolBarMenu;
    private javax.swing.JToolBar jToolBarProcess;
    private javax.swing.JTree jTree;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem openMenuItem;
    private javax.swing.JMenuItem pasteMenuItem;
    private javax.swing.JMenuItem saveAsMenuItem;
    private javax.swing.JMenuItem saveMenuItem;
    // End of variables declaration//GEN-END:variables

    public MutableTreeNode getFolderNode() {
        return folderNode;
    }

    public void setFolderNode(MutableTreeNode folderNode) {
        this.folderNode = folderNode;
    }

    public JToolBar getjToolBarProcess() {
        return jToolBarProcess;
    }

    public void setjToolBarProcess(JToolBar jToolBarProcess) {
        this.jToolBarProcess = jToolBarProcess;
    }

    public RootAlbumTreeNode getAlbumNode() {
        return albumNode;
    }

    public void setAlbumNode(RootAlbumTreeNode albumNode) {
        this.albumNode = albumNode;
    }

    public JPanel getjPanelRight() {
        return jPanelRight;
    }

    public void setjPanelRight(JPanel jPanelRight) {
        this.jPanelRight = jPanelRight;
    }
}
